package com.zecan.blog.config;

import com.zecan.blog.filter.JwtAuthenticationFilter;
import com.zecan.blog.filter.JwtLoginFilter;
import com.zecan.blog.security.handler.*;
import com.zecan.blog.security.service.impl.UserDetailServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

import javax.annotation.Resource;

/**
 * @ClassName SecurityWebConfig
 * @Description
 * @date 2022/10/31 10:25
 * @Version 1.0
 */

@Configuration
@EnableWebSecurity
// 当前注解的作用是 可以不用写构造函数 直接使用final 的属性直接进行构造
@RequiredArgsConstructor
//该注解的作用是开启注解方法 prePostEnabled 注解可以在controller中每个请求写入 在执行前进行权限判断
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Resource
    UserDetailServiceImpl userDetailService;

    @Resource
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Resource
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Resource
    JwtLogoutSuccessHandler logoutSuccessHandler;

    @Resource
    JwtLogoutHandler jwtLogoutHandler;

    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    JwtLoginFilter jwtLoginFilter() throws Exception {
        JwtLoginFilter jwtLoginFilter = new JwtLoginFilter(authenticationManager());
        return jwtLoginFilter;
    }

//    //注入密码加密
    @Bean
    PasswordEncoder PasswordEncoder() {
        return new PasswordEncoder();
    }

    // 直接通过的路径
    private static final String[] URL_WHITELIST = {
            "/user/**",
            "/article/**",
            "/classify/**",
            "/resource/**",
            "/tag/**",
            "/comment/**",
            "/wsBlog/**",
            "/privateWs/**",
            "/elasticsearch/**",
            "/archives/**",
            "/message/**",
            "/login/**",
            "/chatting/**",
            "/friend/list",
            "/logout/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
//                .formLogin()
//                .successHandler(loginSuccessHandler)
//                .failureHandler(loginFailureHandler)
//                .and()

                .logout()
                .logoutUrl("/logout")
                .addLogoutHandler(jwtLogoutHandler)
                .logoutSuccessHandler(logoutSuccessHandler)

                //禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                //配置拦截规则
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().hasAnyAuthority("admin","user")

                //异常处理
                .and()
                .exceptionHandling()
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)

                .and()
                .addFilter(jwtAuthenticationFilter()) //最初始过滤器
                .addFilter(jwtLoginFilter())// 加入登录验证过滤器
                .addFilterBefore(jwtAuthenticationFilter(), LogoutFilter.class);// 在底层过滤器之前添加登出过滤器，否则认证信息会消失

                // 将验证码登录在用户名密码验证过滤器之前

    }


    // ?
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }


    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/user/**");
//        web.ignoring().antMatchers("/article/**");
//        web.ignoring().mvcMatchers("/resource/**");
//        web.ignoring().mvcMatchers("/classify/**");
//    }

}
